package com.blue.seata.business.service;

import com.blue.seata.order.api.remote.RemoteOrderService;
import com.blue.seata.storage.api.remote.RemoteStorageService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author liulei
 * @version 1.0
 */
@Service
public class BusinessService {

    private static final Logger logger = LoggerFactory.getLogger(BusinessService.class);

    @Autowired
    RemoteOrderService orderService;
    @Autowired
    RemoteStorageService storageService;

    @GlobalTransactional(name = "createOrder", timeoutMills = 60000, rollbackFor = Exception.class)
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public boolean buy(String userId, String code, Integer count) throws InterruptedException {
        String xid = RootContext.getXID();
        logger.info("用户购买商品[{}],[{}],[{}]", code, count, xid);
        orderService.create(userId, code, count);
        logger.info("调用订单中心服务成功");
        storageService.minus(code, count);
        logger.info("调用库存中心服务成功");
//        Thread.sleep(120000);
        // 构建人为异常
        if (code.equals("001") && count == 1) {
            throw new RuntimeException("业务中心人为异常..");
        }
        return true;
    }
}
